package com.redxun.auth;

import com.redxun.core.api.sys.ICoreSystemService;
import com.redxun.core.auth.service.impl.AbstractDefaultPermissionServiceImpl;
import com.redxun.core.cache.CacheUtil;
import com.redxun.core.tool.BeanUtil;
import com.redxun.core.tool.StringUtils;
import com.redxun.core.tool.constant.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Set;

/**
 * PermissionServiceImpl.
 * @author aj
 */
@Slf4j
@Service("permissionService")
public class PermissionServiceImpl extends AbstractDefaultPermissionServiceImpl {
    
    @Autowired
    private ICoreSystemService menuService;

    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        return hasPermission(authentication, request.getMethod(), request.getRequestURI());
    }


    @Override
    public Map<String, Set<String>> selectApisByGroupIdsAndRedis() {
        Map<String, Set<String>> menuMap = (Map<String, Set<String>>) CacheUtil.get(CommonConstant.API_REGION, CommonConstant.API_KEY);
        if (BeanUtil.isEmpty(menuMap)) {
            menuMap = menuService.getUrlGroupIdMap();
            CacheUtil.set(CommonConstant.API_REGION, CommonConstant.API_KEY, menuMap);
        }
        for (String url : menuMap.keySet()) {
            if (StringUtils.isNotEmpty(url) && url.contains("**")) {
                FUZZY_URL_LIST.add(url);
            }
        }
        return menuMap;
    }
}
